package com.eazy.lksy.web.service.impl;

import java.util.List;
import java.util.Map;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.eazy.lksy.web.core.dao.CommonServiceImpl;
import com.eazy.lksy.web.dao.UserDao;
import com.eazy.lksy.web.exception.ServiceException;
import com.eazy.lksy.web.model.Role;
import com.eazy.lksy.web.service.UserService;
import com.eazy.lksy.web.utils.Bundle;
import com.eazy.lksy.web.view.vo.RequestUserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eazy.lksy.web.dao.RoleDao;
import com.eazy.lksy.web.service.RoleService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class RoleServiceImpl extends CommonServiceImpl<Role> implements RoleService {

	@Autowired
	private RoleDao roleDao;
	@Autowired
	private UserService userService;


	@Override
	public String addRole(Map<String, String> map) {
		return roleDao.addRole(map);
	}

	@Override
	public List<Map<String, Object>> getRolePermissions(String id) {
		return roleDao.getRolePermissions(id);
	}

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public void addUserRole(RequestUserRole request) {
		if(ObjectUtil.isEmpty(request.getRoleId())) {
			throw new ServiceException("角色不能为空！！！");
		}
		if(StrUtil.isEmptyIfStr(request.getUser_id())) {
			throw new ServiceException("用户不能为空！");
		}
		roleDao.deleteUserRole(request.getUser_id());

		request.getRoleId().stream().forEach((roleId) ->{
			userService.addUserRole(request.getUser_id(), roleId);
		});
	}

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public void deleteUser(String id) {
		try {
			userService.deleteById(id);
			roleDao.deleteUserRole(id);
		} catch (Exception ex) {
			throw new ServiceException("删除数据失败");
		}
	}

	@Override
	public List<Role> toRoles(String roleId) {
		List<Map<String, Object>> self_role = getRoles(roleId); // 用户拥有角色
		List<Role> all_role = select(); // 所有角色

		for (Role all : all_role) {
			all.setPoint(0);
			for (Map<String,Object> self : self_role) {
				if(Bundle.convStr(self.get("ID")).equals(Bundle.convStr(all.getId()))) {
					all.setPoint(1);
				}
			}
		}
		return all_role;
	}

	@Override
	public List<Map<String, Object>> getRoles(String cust_id) {
		return roleDao.getRoles(cust_id);
	}

	@Override
	public void deleteUserRole(String user_id) {
		roleDao.deleteUserRole(user_id);
	}

	@Override
	public void addRolePermission(String role_id, String permission_id) {
		roleDao.addRolePermission(role_id, permission_id);
	}

	@Override
	public Map<String, Object> getRole(String role_id) {
		return roleDao.getRole(role_id);
	}

	@Override
	public void updateRole(Map<String, String> map) {
		roleDao.updateRole(map);
	}
	

}
